package com.thread.book.book2;

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.atomic.AtomicReferenceFieldUpdater;

public class AtomicReferce01 {

    public static void main(String[] args) {
        AtomicReference<User> ar = new AtomicReference();
        final User houzheng = new User("houzheng", 25);
        ar.set(houzheng);
        //比较是否是原来的对象,再更新
        ar.compareAndSet(houzheng, new User("yaozhen", 25));
        System.out.println(ar.get().name);//yaozhen
        final User heyi = new User("heyi", 30);
        //获取旧值,并设置新值,取旧对象的名字,新对象参数的年龄
        //需要函数参数BinaryOperator: 接受两个参数,返回一个
        ar.getAndAccumulate(heyi, (x, y) -> new User(x.getName(), y.getAge()));
        System.out.println(ar.get().toString());//User{name='yaozhen', age=30}
    }


    static class User {
        private String name;
        private int age;

        public User(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "User{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }
    }
}
